package com.wfm.leetcode.editor.cn;

import com.wfm.common.TreeNode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树层序遍历
 * 遍历每一层，得到最右边那个数字
 */
public class P199二叉树的右视图{
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        // 层序遍历
        List<List<Integer>> lists = levelOrder(root);
        // 遍历每一层，得到最右边那个数字
        for (int i = 0; i < lists.size(); i++) {
            List<Integer> integers = lists.get(i);
            Integer integer = integers.get(integers.size() - 1);
            result.add(integer);
        }
        return result;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root == null) {
            return res;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> tmp = new ArrayList<>();
            int curSize = queue.size();
            for (int i = 0; i < curSize; i++) {
                TreeNode poll = queue.poll();
                tmp.add(poll.val);
                if (poll.left != null)
                    queue.offer(poll.left);
                if (poll.right != null)
                    queue.offer(poll.right);
            }
            res.add(tmp);
        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) { 
        Solution solution = new P199二叉树的右视图().new Solution();
    }
}